package com.ay.weixin.fdc.front.kanfang.event;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;

import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.json.JObject;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.FDCProjectStatus;
import com.ay.weixin.config.types.KanFangProgress;
import com.ay.weixin.config.types.KanFangType;
import com.ay.weixin.config.types.UserStatus;
import com.ay.weixin.fdc.admin.category.domain.CategoryLoader;
import com.ay.weixin.fdc.boss.kanfang.db.IbatisKanFangDao;
import com.ay.weixin.fdc.boss.kanfang.db.IbatisKanFangFlowDao;
import com.ay.weixin.fdc.boss.kanfang.domain.KanFang;
import com.ay.weixin.fdc.boss.kanfang.domain.KanFangFlow;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectDao;
import com.ay.weixin.fdc.boss.project.domain.FDCProject;
import com.ay.weixin.fdc.boss.user.db.FDCAgentDao;
import com.ay.weixin.fdc.boss.user.domain.FDCAgent;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;
import com.ay.weixin.fdc.front.usercenter.event.UserInfoAccess;
import com.ay.weixin.mail.domain.Email;
import com.ay.weixin.mail.domain.KanFangEmailNotify;
import com.ay.weixin.templatereply.domain.ReplyMsg;
import com.ay.weixin.templatereply.domain.TemplateReply;

/**
 * 
 * 修改建议
 *  * 预约看房和openid绑定
 * */
public class KanFangEvent extends Event implements Before{
	private IbatisProjectDao project_dao;
	private IbatisKanFangDao kanfang_dao;
	private IbatisKanFangFlowDao flow_dao;
	private FDCAgentDao user_dao;
	private CategoryLoader cl;
	private UserInfoAccess user_access;
	private KanFangEmailNotify emailNotify;
	@Override
	public void init_property() throws Exception {
		kanfang_dao=Container.get(IbatisKanFangDao.class);
		project_dao=Container.get(IbatisProjectDao.class);
		flow_dao=Container.get(IbatisKanFangFlowDao.class);
		user_dao=Container.get(FDCAgentDao.class);
		user_access=Container.get(UserInfoAccess.class);
		cl=Container.get(CategoryLoader.class);
		emailNotify=Container.get(KanFangEmailNotify.class);
			}

	@Override
	public String default_handling_path() {
		return "/fdc/kanfang/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long wxproject_id=el.queryPathInt(2);
		
		if(!el.getBool("is_weixin")&&ProjectConfig._bool(wxproject_id,"sys.weixin_only")){
			el.text("invalid visit");
			return;
		}
		UserWeiXinInfo weixin_info=el.getSessionAttr("weixin_info",UserWeiXinInfo.class);
		if(weixin_info==null){
			user_access.open_id_check(el,"/fdc/kanfang/",wxproject_id);
			return ;
		}
		if(StringHelper.equals(el.queryPath(3), "")){
			index(el,wxproject_id);
		}else if(StringHelper.equals(el.queryPath(3), "book")){
			String result=book(el,wxproject_id);
			if(result!=null){
				el.text(result);
			}
		}
	}
	
	public static String check_user_recommand_number(long wxproject_id,FDCAgent user){
		Date d=user.getRecommand_date();
		if(d==null){
			user.setRecommand_date(new Date(System.currentTimeMillis()));
			user.setToday_recommand_num(0);
		}else{
			Date today=new Date(System.currentTimeMillis());
			if(d.getDate()!=today.getDate()){
				user.setRecommand_date(new Date(System.currentTimeMillis()));
				user.setToday_recommand_num(0);
			}else {
				if(user.getToday_recommand_num()>=ProjectConfig.getInt(wxproject_id,"fdc_kanfang.max_recommand_submit")){
					return "max_exceed";
				}
			}
		}
		return null;
	}
	
	private String book(EventLoader el,long wxproject_id) throws IOException{
		FDCAgent user=el.getSessionAttr("user",FDCAgent.class);
		if(user==null&&el.getSessionAttr("book")!=null){
			return el.i18("fdc_project.already.book");
		}
		
		if(user!=null){
			if(!StringHelper.equals(user.getStatus(),"ok")){
				try {
					user=user_dao.getById(user.getId());
					el.setSessionAttr("user",user);
				} catch (SQLException e) {
					return el.i18("fdc.project.db.failure");
				}
				el.setSessionAttr("user",user);
				if(!StringHelper.equals(user.getStatus(),"ok")){
					return String.format(el.i18("usercenter.status.isabnormal"),UserStatus.getByName(user.getStatus()).getDesc());
				}
			}
			if(user.getBlack_list_times()>ProjectConfig.getInt(wxproject_id,"fdc_kanfang.user_black_list_limit")){
				return String.format(el.i18("usercenter.status.isabnormal"),"黑名单");
			}
			String check_result=check_user_recommand_number(wxproject_id,user);
			if(check_result!=null){
				return el.i18("fdc_project.recommand.max.exceed");
			}
		}
		
		
		String name=el.getStr("username");
		String sex=el.getStr("sex");
		String contact=el.getStr("contact");
		String gohousedate=el.getStr("gohousedate");
		String birthday=el.getStr("birthday");
		String buyexper=el.getStr("buyexper");
		long project_id=el.getLong("project_id");
		String remark=el.getStr("remark");
		
		if(StringHelper.isNull(contact)){
			return el.i18("fdc_project.contact.not.empty");
		}
		
		if(StringHelper.isNull(name)){
			return el.i18("fdc_project.name.not.empty");
		}
		
		if(name.length()>Keys.getInt("fdc_usercenter.register_name_max_length")||name.length()<Keys.getInt("fdc_usercenter.register_name_min_length")){
			return String.format(el.i18("fdc_usercenter.name.not.valid"), Keys.getInt("fdc_usercenter.register_name_min_length"),Keys.getInt("fdc_usercenter.register_name_max_length"));
		}
		
		if(!StringHelper.isLong(contact)||contact.length()!=Keys.getInt("fdc_usercenter.register_phone_length")){
			return String.format(el.i18("fdc_usercenter.phone.not.valid"), Keys.getInt("fdc_usercenter.register_phone_length"));
		}
		
		if(remark.length()>Keys.getInt("fdc_kanfang.remark_max_length")){
			return String.format(el.i18("fdc_remark.max.length.exceed"), Keys.getInt("fdc_kanfang.remark_max_length"));
		}
		
		try {
			if(kanfang_dao.hasLogged(wxproject_id,contact, project_id)){
				return el.i18("fdc_project.already.book");
			}
		} catch (SQLException e1) {
			return el.i18("fdc.project.db.failure");
		}
		
		
		FDCProject project=null;
		
		try {
			project=project_dao.get(project_id);
		} catch (SQLException e1) {
			e1.printStackTrace();
			return el.i18("fdc.project.db.failure");
		}
		
		if(project==null){
			return el.i18("fdc_project.please.select.project");
		}
		
		KanFang kanfang=new KanFang();
		kanfang.setName(name);
		kanfang.setSex(sex);
		kanfang.setBuyexper(buyexper);
		kanfang.setContact(contact);
		kanfang.setProgress(KanFangProgress.START.getValue());
		kanfang.setProject_id(project_id);
		kanfang.setRemark(remark);
		kanfang.setUpdate_date(new Date(System.currentTimeMillis()));
		kanfang.setStatus(KanFang.STATUS_NONE);
		kanfang.setType(KanFangType.BOOK.getValue());
		kanfang.setCreate_time(new Date(System.currentTimeMillis()));
		kanfang.setSalesman(el.getLong("salesman"));
		if(user!=null){
			kanfang.setRecommend_user(user.getId());
			user.inc_recommand_num();
			if(!contact.equals(user.getPhone())){
				kanfang.setStatus(KanFangType.RECOMMAND.getValue());
			}
			try {
				user_dao.update(user);
			} catch (SQLException e) {
				e.printStackTrace();
				return el.i18("fdc.project.db.failure");
			}
		}
		
		try {
			if(StringHelper.isNotNull(birthday)){kanfang.setBirthday(new SimpleDateFormat("dd/mm/yyyy").parse(birthday));}
			if(StringHelper.isNotNull(gohousedate)){kanfang.setGohousedate(gohousedate);};
		} catch (ParseException e) {
			e.printStackTrace();
			return el.i18("fdc.project.db.failure");
		}
		try {
			kanfang_dao.insert(kanfang);
			kanfang=kanfang_dao.getLastBook(wxproject_id,contact);
		} catch (SQLException e) {
			e.printStackTrace();
			return el.i18("fdc.project.db.failure");
		}
		KanFangFlow flow=new KanFangFlow();
		flow.setCurrent_status(kanfang.getStatus());
		flow.setOper_timestamp(System.currentTimeMillis());
		flow.setKf_id(kanfang.getId());
		flow.setOper(0);
		try {
			flow_dao.insert(flow);
		} catch (SQLException e) {
			e.printStackTrace();
			return el.i18("fdc.project.db.failure");
		}
		
		if(user!=null){
			Recommand.recommand_income(el,wxproject_id,user);
		}
		UserWeiXinInfo weixin_info=el.getSessionAttr("weixin_info",UserWeiXinInfo.class);
		el.setSessionAttr("book",1);
		reply(wxproject_id,name,weixin_info.getId(),project,kanfang.getGohousedate(),contact,"请您准时到达看房。");
		sendEmail(wxproject_id,project,kanfang,el);
		return "1";
	}
	
	public void sendEmail(long wxproject_id,FDCProject project,KanFang kanfang,EventLoader el){
		if(ProjectConfig.getBool(wxproject_id,"fdc_kanfang.email_notify_enable")&&Email.isEmail( ProjectConfig.getStr(wxproject_id,"fdc_kanfang.notify_email"))){
			try{
				emailNotify.sendKanFangNotify(wxproject_id, kanfang.getName(), kanfang.getContact(), kanfang.getGohousedate(), 
					project.getTitle(), ProjectConfig.getStr(wxproject_id,"fdc_kanfang.notify_email"), Config.xpathgetStr("server_info.root")+"/menu", el);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	public static void reply(long wxproject_id,String ropenid,String name,FDCProject project,String onvisit_date,String contact,String _remark){
		if(StringHelper.isNull(ropenid))return;
		JObject params=new JObject();
		JObject first=new JObject();
		first.put("value", "您已经成功提交信息，我们将尽快联系！(看房客户:"+name+",联系电话:"+contact+")");
		first.put("color", ReplyMsg.BLUE);
		params.put("first", first);
		
		JObject apartmentName=new JObject();
		apartmentName.put("value", project.getTitle());
		apartmentName.put("color", ReplyMsg.BLUE);
		params.put("apartmentName", apartmentName);
		
		JObject address=new JObject();
		address.put("value", project.getLocation());
		address.put("color", ReplyMsg.BLUE);
		params.put("address", address);
		
		JObject roomNumber=new JObject();
		roomNumber.put("value","待定");
		roomNumber.put("color", ReplyMsg.LIGHT_BLACK);
		params.put("roomNumber", roomNumber);
		
		JObject time=new JObject();
		time.put("value",onvisit_date);
		time.put("color", ReplyMsg.BLUE);
		params.put("time", time);
		
		JObject remark=new JObject();
		remark.put("value",_remark);
		remark.put("color", ReplyMsg.BLUE);
		params.put("remark", remark);
		
		ReplyMsg msg=new ReplyMsg();
		msg.setMsg_link("");
		msg.setOpenid(ropenid);
		msg.setWxproject_id(wxproject_id);
		msg.setTemplate_id(ProjectConfig.getStr(wxproject_id,"fdc_kanfang.book_template_msg_id"));
		msg.setTopcolor(ReplyMsg.BLUE);
		msg.setData_params(params);
		TemplateReply.asyReply(msg);
	}

	private void index(EventLoader el,long wxproject_id) throws IOException, ServletException{
		
		List<FDCProject> plist=null;
		List<FDCAgent> salesman=null;
		try {
			plist=project_dao.getAllByFront(wxproject_id,FDCProjectStatus.onsale.getCode());
			salesman=user_dao.getAllSalesmanByStatus(wxproject_id,"ok");
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg",el.i18("fdc.project.db.failure"));
		}
		el.setAttr("salesList", salesman);
		el.setAttr("project_list", plist);
		el.template("/WEB-INF/template/app/"+wxproject_id+"/fdc/kanfang/yuyue.vm");
	}

	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		long wxproject_id=bl.queryPathInt(2);
		bl.setAttr("mc_user_enable_salesman", ProjectConfig.getBool(wxproject_id,"fdc_usercenter.enable_salesman"));
	}

}
